﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NewsMine.Storage
{
    public class QueueManagerOnFileSystem : IQueueManager
    {

        public void CreateQueue(string name)
        {
            ValidateQueueName(name);

            string queueDirectoryName = GetQueueFolderByQueueName(name);

            if (Directory.Exists(queueDirectoryName))
            {
                throw new ApplicationException("Already this queuest is exists");
            }

            Directory.CreateDirectory(queueDirectoryName);

        }

        private static string GetQueueFolderByQueueName(string name)
        {
            string queueName = Path.Combine(Configuration.ConfigurationManager.QueuesBaseFolder, name);
            return queueName;
        }

        private void ValidateQueueName(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(string.Format("Invalid queue name {0}, Please provide the valid queue name", name));
            }
        }

        public void DeleteQueue(string name)
        {
            ValidateQueueName(name);

            string queueName = Path.Combine(Configuration.ConfigurationManager.QueuesBaseFolder, name);

            if (!Directory.Exists(queueName))
            {
                throw new ApplicationException("The specified queue is not exists exists. Queue name : " + queueName);
            }

            Directory.Delete(queueName,true);
        }

        public void ClearQueue(string name)
        {
            var q = GetQueueByName(name);
            q.ClearQueue();
        }

        public List<string> ListAllQueueNames()
        {
            return new List<string>(Directory.GetDirectories(Configuration.ConfigurationManager.QueuesBaseFolder));
        }

        public IPersistedQueue GetQueueByName(string name)
        {
            string queueDirectoryName = GetQueueFolderByQueueName(name);

            if (!Directory.Exists(queueDirectoryName))
            {
                return null;
            }

            return new QueueOnFileSystem(queueDirectoryName);
        }

        string defaultQueueName = "Default";

        public IPersistedQueue GetDefaultQueue()
        {
            CreateDefaultQueueIfNotCreated(defaultQueueName);

            return GetQueueByName(defaultQueueName);
        }

        private void CreateDefaultQueueIfNotCreated(string name)
        {

            string queueDirectoryName = GetQueueFolderByQueueName(name);

            if (Directory.Exists(queueDirectoryName))
            {
                return;
            }

            Directory.CreateDirectory(queueDirectoryName);

        }
    }
}
